package com.list.model.specific;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.FileManager;
import com.list.model.abstracts.BaseModel;
import com.list.model.utils.FileAddress;
import com.list.model.utils.RelFinderLog;

public class OntoModel extends BaseModel{
	
	private String XMLSCHEMA_PREFIX = "http://www.w3.org/2001/XMLSchema#";
	private String RDFSCHEMA_PREFIX = "http://www.w3.org/2000/01/rdf-schema#";
	private String RDF_PREFIX = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
	
	public OntoModel() {
		super(ModelFactory.createDefaultModel());
	}
	
	@Override
	public void loadOntology() {
		InputStream in = FileManager.get().open(FileAddress.ONTO_FILE_ADDRESS);
		if (in == null) {
			RelFinderLog.log(RelFinderLog.DETAIL, "File Not Found !!!. \n");
		}else {
			getModel().read(in, null);
//			write(FileAddress.TRIPLE_FILE_ADDRESS);
		}
	}
	
	@Override
	public Model getInstaceModel() {
		Model newModel = ModelFactory.createDefaultModel();
		StmtIterator listStatements = getModel().listStatements();
		while(listStatements.hasNext()) {
			Statement stmt = listStatements.next();
			RDFNode object = stmt.getObject();
			Property property = stmt.getPredicate();
			if(object.isURIResource()) {
				if(!property.getURI().startsWith(RDFSCHEMA_PREFIX)
						&&!property.getURI().startsWith(RDF_PREFIX)
						&&!object.asResource().getURI().startsWith(XMLSCHEMA_PREFIX)){
					newModel.add(stmt);
				}
			}
		}
		getModel().close();
		setModel(newModel);
//		write(FileAddress.INSTANCE_TRIPLE_FILE_ADDRESS);
		return getModel();
	}
	
	private void write(String filename) {
        try {
            File file = new File(filename);
            file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			PrintWriter pw = new PrintWriter(bos);
			StmtIterator stmtIterator = getModel().listStatements();
			while (stmtIterator.hasNext()) {
				Statement stmt = stmtIterator.next();
//				RDFNode object = stmt.getObject();
//				if (object.isURIResource()){
					pw.write("< " + stmt.getSubject() + "> , <"
							+ stmt.getPredicate() + " > , <" + stmt.getObject()
							+ "> \n");
//				}
			}
			pw.flush();
			pw.close();
			bos.close();
			fos.close();
		} catch (IOException ex) {
            ex.printStackTrace();
        }
	}
	
}
